/*
 * 1000:json 解析错误
 * 2000:数据库错误
 * 3000:权限不足
 * 4000:参数错误
 * 5000:网络错误
 * 6000:文件访问错误
 * 7000:未知错误
 * 10000:自定义错误
 */
#[derive(Debug)]
pub struct MyError {
    code: u32,
    hint: String,
    message: String,
}

impl MyError {
    pub fn new(code: u32, hint: String, message: String) -> Self {
        MyError {
            code,
            hint,
            message,
        }
    }

    pub fn parse_error(hint: String, message: String) -> Self {
        MyError::new(1000, hint, message)
    }

    pub fn database_error(hint: String, message: String) -> Self {
        MyError::new(2000, hint, message)
    }

    pub fn permission_error(hint: String, message: String) -> Self {
        MyError::new(3000, hint, message)
    }

    pub fn parameter_error(hint: String, message: String) -> Self {
        MyError::new(4000, hint, message)
    }

    pub fn network_error(hint: String, message: String) -> Self {
        MyError::new(5000, hint, message)
    }

    pub fn file_access_error(hint: String, message: String) -> Self {
        MyError::new(6000, hint, message)
    }

    pub fn unknown_error(hint: String, message: String) -> Self {
        MyError::new(7000, hint, message)
    }

    pub fn custom_error(code: u32, hint: String, message: String) -> Self {
        MyError::new(code, hint, message)
    }
}

impl std::fmt::Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}:{}", self.code, self.message)
    }
}

impl std::error::Error for MyError {}

impl serde::Serialize for MyError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{}:{} - {}", self.code, self.hint, self.message))
    }
}

impl From<rusqlite::Error> for MyError {
    fn from(err: rusqlite::Error) -> Self {
        MyError::database_error(format!("{}", err), err.to_string())
    }
}
